/*
 * Copyright (C) 2009 Internal Innovation Technology(IIT)
 * 
 */
package com.iitbd.hxcalc;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.SwingConstants;
import org.apache.log4j.Logger;
import org.supercsv.io.CsvListReader;
import org.supercsv.io.CsvListWriter;
import org.supercsv.prefs.CsvPreference;

/**
 *
 * @author Prasun Kanti Howlader <prasun@iitbd.com>
 */
public class FileInputDialog extends javax.swing.JDialog {

    private HxcalcUI parent = null;
    CsvPreference preference = null;
    CsvListReader parser = null;
    List<String> values = new ArrayList<String>();
    boolean csvread = false;
    Iterator itr = null;
    int increment = 0;
    Character delimiter;
    private static Logger logger = Logger.getLogger(FileInputDialog.class.getName());

    /**
     * Creates new form FileInputDialog
     */
    public FileInputDialog(javax.swing.JFrame parent, String title) {
        super(parent, title);
        this.parent = (HxcalcUI) parent;
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        btgSepataor = new javax.swing.ButtonGroup();
        btgDecimal = new javax.swing.ButtonGroup();
        btnLine = new javax.swing.JButton();
        btnFile = new javax.swing.JButton();
        btnExit = new javax.swing.JButton();
        btnReset = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        cmbFile = new javax.swing.JComboBox();
        rdTab = new javax.swing.JRadioButton();
        rdSemicolon = new javax.swing.JRadioButton();
        rdDot = new javax.swing.JRadioButton();
        rdComma = new javax.swing.JRadioButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setModal(true);
        setResizable(false);

        btnLine.setFont(new java.awt.Font("Dialog", 0, 11)); // NOI18N
        btnLine.setText(Resources.getString("Process Line"));
        btnLine.setHorizontalAlignment(SwingConstants.CENTER);
        btnLine.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnLine.addActionListener(new ButtonHandler());

        btnFile.setFont(new java.awt.Font("Dialog", 0, 11)); // NOI18N
        btnFile.setText(Resources.getString("Process File"));
        btnFile.setHorizontalAlignment(SwingConstants.CENTER);
        btnFile.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnFile.addActionListener(new ButtonHandler());

        btnExit.setFont(new java.awt.Font("Dialog", 0, 11)); // NOI18N
        btnExit.setText(Resources.getString("Close"));
        btnExit.setHorizontalAlignment(SwingConstants.CENTER);
        btnExit.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnExit.addActionListener(new ButtonHandler());

        btnReset.setFont(new java.awt.Font("Dialog", 0, 11)); // NOI18N
        btnReset.setText(Resources.getString("Output.Reset"));
        btnReset.setHorizontalAlignment(SwingConstants.CENTER);
        btnReset.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

        jLabel4.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
        jLabel4.setText(Resources.getString("Input File"));

        jLabel1.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
        jLabel1.setText(Resources.getString("File Name"));

        jLabel2.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
        jLabel2.setText(Resources.getString("Separator"));

        jLabel3.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
        jLabel3.setText(Resources.getString("Decimal"));

        cmbFile.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
        cmbFile.addItem("Input.csv");
        cmbFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbFileActionPerformed(evt);
            }
        });

        btgSepataor.add(rdTab);
        rdTab.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
        rdTab.setSelected(true);
        rdTab.setText(Resources.getString("Tab"));

        btgSepataor.add(rdSemicolon);
        rdSemicolon.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
        rdSemicolon.setText(Resources.getString("Semicolon"));

        btgDecimal.add(rdDot);
        rdDot.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
        rdDot.setSelected(true);
        rdDot.setText(Resources.getString("Dot"));

        btgDecimal.add(rdComma);
        rdComma.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
        rdComma.setText(Resources.getString("Comma"));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(74, 74, 74)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(rdDot)
                                    .addComponent(rdTab))
                                .addGap(52, 52, 52)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(rdSemicolon)
                                    .addComponent(rdComma))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addComponent(cmbFile, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addComponent(jLabel4)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnLine, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnFile, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnReset, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnExit)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel4)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(rdTab)
                        .addComponent(rdSemicolon))
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(rdDot)
                        .addComponent(rdComma)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 45, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnExit)
                    .addComponent(btnReset)
                    .addComponent(btnFile)
                    .addComponent(btnLine))
                .addGap(20, 20, 20))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cmbFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbFileActionPerformed
        JFileChooser chooser = new JFileChooser();
        int returnVal = chooser.showSaveDialog(parent);
        File filename = chooser.getSelectedFile();
        //cmbFile.setModel(new javax.swing.DefaultComboBoxModel(new String[]{filename.getAbsolutePath()}));
        cmbFile.setModel(new javax.swing.DefaultComboBoxModel(new String[]{filename.getName()}));
        cmbFile.setToolTipText(filename.getAbsolutePath());

    }//GEN-LAST:event_cmbFileActionPerformed

    private void printValues(String s) {
        // String[] str = s.split(";", -1);
        String[] str = s.split(";", -1);
        for (int i = 0; i < 14; i++) {
            if (str[0] != " ") {

                System.out.print(str[i] + "\t");
            }
            char ch = '.';
            if (rdComma.isSelected()) {
                ch = ',';
            }
            parent.inputwindow.txtTemp.setText(str[1].replace(ch, '.'));
            parent.inputwindow.txtPre.setText(str[2]);
            if (str[5].equals("ice")) {
                parent.inputwindow.rdIce.setSelected(true);
            } else {
                parent.inputwindow.rdWater.setSelected(true);
            }
            if (str[6].equals("ice")) {
                parent.inputwindow.rdOIce.setSelected(true);
            } else {
                parent.inputwindow.rdOWater.setSelected(true);
            }
            if (str[7].equals("yes")) {
                //parent.inputwindow.cmbExtended.setSelectedIndex(1);
                parent.inputwindow.txtSTemp.setText(str[8].replace(',', '.'));
                parent.inputwindow.txtSPre.setText(str[9]);
            } else {
                //parent.inputwindow.cmbExtended.setSelectedIndex(0);
            }
            String carrerGas = str[10].toLowerCase();

            parent.inputwindow.cmbGas.setSelectedItem(carrerGas);
            if (carrerGas.equals("othergas")) {
                parent.inputwindow.txtMassMolar.setText(str[11]);
                parent.inputwindow.txtCap.setText(str[12]);
                parent.inputwindow.txtBoil.setText(str[13]);

            }


        }




    }

    private boolean readCSV() {
        String temp = null;
        List<String> as = null;
        if (rdTab.isSelected()) {
            preference = new CsvPreference('"', '\t', "\n");
            delimiter = '\t';
        } else {
            preference = new CsvPreference('"', ';', "\n");
            delimiter = ';';
        }

        try {
            parser = new CsvListReader(new FileReader((String) cmbFile.getItemAt(0)), preference);
            as = parser.read();


            while (as != null) {

                if (parser.getLineNumber() > 3) {

                    for (String s : as) {

                        values.add(s);


                    }


                }

                as = parser.read();
            }
            itr = values.iterator();
            csvread = true;
        } catch (FileNotFoundException ex) {
            csvread = false;
            logger.info("CSV File not Found");

        } catch (IOException io) {
            csvread = false;
        }

        return csvread;

    }

    private void writeCSV() throws IOException {
        StringWriter sw = new StringWriter();
        CsvListWriter writer = new CsvListWriter(sw, CsvPreference.STANDARD_PREFERENCE);


        for (int i = 0; i < 4; i++) {
            writer.write(values);
        }
        writer.close();
    }

    class ButtonHandler implements ActionListener {

        public void actionPerformed(ActionEvent ae) {
            JButton button = (JButton) ae.getSource();
            if (button == btnExit) {
                dispose();
            } else if (button == btnLine) {
                if (csvread) {
                    if (increment < values.size()) {
                        String s = values.get(increment);
                        System.out.println(s);
                        printValues(s);
                        increment++;
                    } else {
                        System.out.println("All line process");
                    }
                } else {
                    readCSV();
                    if (increment < values.size()) {
                        String s = values.get(increment);
                        System.out.println(s);
                        printValues(s);
                        increment++;
                    } else {
                        System.out.println("All line process");
                    }
                }

            } else if (button == btnFile) {
            }


        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup btgDecimal;
    private javax.swing.ButtonGroup btgSepataor;
    private javax.swing.JButton btnExit;
    private javax.swing.JButton btnFile;
    private javax.swing.JButton btnLine;
    private javax.swing.JButton btnReset;
    private javax.swing.JComboBox cmbFile;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JRadioButton rdComma;
    private javax.swing.JRadioButton rdDot;
    private javax.swing.JRadioButton rdSemicolon;
    private javax.swing.JRadioButton rdTab;
    // End of variables declaration//GEN-END:variables
}
